package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.DashboardSummary;
import com.ruoyi.livedemo.entity.FavoriteQuote;
import com.ruoyi.livedemo.entity.GoalItem;
import com.ruoyi.livedemo.mapper.DiaryEntryMapper;
import com.ruoyi.livedemo.mapper.FavoriteQuoteMapper;
import com.ruoyi.livedemo.mapper.GoalItemMapper;
import com.ruoyi.livedemo.mapper.ReminderMapper;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class DashboardService {

    private final GoalItemMapper goalItemMapper;
    private final DiaryEntryMapper diaryEntryMapper;
    private final ReminderMapper reminderMapper;
    private final FavoriteQuoteMapper favoriteQuoteMapper;

    public DashboardSummary build(Long userId) {
        // 汇总仪表盘需要展示的数据：目标、日记、提醒与暖心语录
        List<GoalItem> goals = goalItemMapper.findByUser(userId);
        int completed = (int) goals.stream()
                .filter(goal -> "DONE".equalsIgnoreCase(goal.getStatus())
                        || goal.getProgressRatio() != null && goal.getProgressRatio() >= 100)
                .count();

        long diaryCount = diaryEntryMapper.countByUser(userId);
        int reminderCount = reminderMapper.findByUser(userId).size();

        List<FavoriteQuote> quotes = favoriteQuoteMapper.findByUser(userId);
        List<String> cheer = new ArrayList<>();
        quotes.stream().limit(3).forEach(q -> cheer.add(q.getContent()));
        if (cheer.isEmpty()) {
            cheer.add("保持热爱，把每一份小确幸都珍藏进你们的纪念册。");
            cheer.add("记得和TA说声早安，也别忘了睡前的轻声晚安。");
        }

        return DashboardSummary.builder()
                .greeting("亲爱的，今天也要好好生活，让彼此的故事继续闪闪发光~")
                .today(LocalDate.now())
                .goalCount(goals.size())
                .goalCompleted(completed)
                .diaryCount((int) diaryCount)
                .reminderCount(reminderCount)
                .cheerMessages(cheer)
                .build();
    }
}
